#include "xfile_crypt.h"
#include "xread_task.h"
#include "xcrypt_task.h"
#include "xwrite_task.h"

bool XFileCrypt::start(const std::string &infile, const std::string &outfile, 
    const std::string &passwd, bool isEncrypt)
{
    std::shared_ptr<std::pmr::memory_resource> mp(new std::pmr::synchronized_pool_resource);

    readTask_ = std::make_shared<XReadTask>();
    readTask_->init(infile);
    readTask_->setMemPool(mp);

    cryptTask_ = std::make_shared<XCryptTask>();
    cryptTask_->init(passwd);
    cryptTask_->setMemPool(mp);
    cryptTask_->setState(isEncrypt);
    readTask_->setNext(cryptTask_);

    writeTask_ = std::make_shared<XWriteTask>();
    writeTask_->setMemPool(mp);
    writeTask_->init(outfile);
    cryptTask_->setNext(writeTask_);

    readTask_->start();
    cryptTask_->start();
    writeTask_->start();

    return true;
}

void XFileCrypt::wait()
{
    if (readTask_) {
        readTask_->wait();
    }
    if (cryptTask_) {
        cryptTask_->wait();
    }
    if (writeTask_) {
        writeTask_->wait();
    }
}
